import { InfiniteScroll, List } from "antd-mobile";
import { useState } from "react";
import { sleep } from "antd-mobile/es/utils/sleep";
import { useDispatch, useSelector } from "react-redux";
import { getArticleList } from "@/store/actions/home";
import styles from "./index.module.scss";
import { RootState } from "@/types/store";
import Item from "antd-mobile/es/components/dropdown/item";
import ArticleItem from "../ArticleItem";
import { useHistory } from "react-router-dom";
import article from "@/store/reducers/article";
let count = 0;
type Props = {
  channelId: number;
  type: number;
};
// 模拟请求数据的异步函数
async function mockRequest() {
  if (count >= 5) {
    return [];
  }
  await sleep(2000);
  count++;
  return [
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
  ];
}
const ArticleList = ({ channelId }: Props) => {
  const [data, setData] = useState<string[]>([]);
  const [hasMore, setHasMore] = useState(true);
  const dispatch: any = useDispatch();
  const history = useHistory();
  const renderArticleList = () => {
    return results.map((item: any, index: any) => {
      console.log(item, "11111111111111111");
      // <div onClick={() => history.push(`/Article/${item}`)}></div>;
      // renderArticleList();
    });
  };
  // 加载更多数据的函数
  async function loadMore() {
    const timestamp = +new Date() + ""; // 获取当前时间戳
    const append = await mockRequest(); // 模拟请求数据
    setData((val) => [...val, ...append]); // 更新数据列表
    setHasMore(append.length > 0); // 更新是否还有更多数据的状态
    await dispatch(getArticleList(channelId, timestamp)); // 触发异步获取文章列表的 action
  }

  // 获取当前频道的文章列表数据
  const { channelArticles } = useSelector((state: RootState) => state.home);

  // 获取当前频道的文章列表信息，如果不存在则设置默认值
  const currentChannelArticle = channelArticles[channelId] ?? {
    pre_timestamp: Date.now() + "", // 设置当前时间戳作为默认时间戳
    results: [], // 设置空数组作为默认文章列表
  };
  const { pre_timestamp, results } = currentChannelArticle; // 解构获取文章列表信息
  return (
    <div className={styles.root}>
      {/* 遍历渲染文章列表中的每一项 */}
      {results.map((item, index) => (
        <div
          onClick={() => history.push(`/article/${item.art_id}`)}
      
          key={index}
          className="article-item"
        >
          {/* ArticleItem 组件需要传入 type 属性 */}
          <ArticleItem
            type={0}
            title={item.title}
            pubdate={item.pubdate}
            comm_count={item.comm_count}
            aut_name={item.aut_name}
            art_id={item.art_id}
            images={item.cover.images}
          />
        </div>
      ))}
      {/* 使用 InfiniteScroll 组件实现无限滚动加载更多数据 */}
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
    </div>
  );
};

export default ArticleList;
